package ar.edu.uba.fi.jmit.monitorengine.backend.client.view;

import java.util.List;

import ar.edu.uba.fi.jmit.monitorengine.backend.shared.dto.VisualizerDTO;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class VisualizersPanel extends VerticalPanel implements ValueChangeHandler<String> {
	
	private Grid visualizersGrid;
	
	public VisualizersPanel() {
		super();
		this.setSize("800px", "100%");
		this.add(new HTML("<h1>Visualizers</h1>"));
		visualizersGrid = new Grid(0, 3);
		visualizersGrid.setTitle("Visualizers");
		this.add(visualizersGrid);
	}
	
	@Override
	protected void onLoad() {
		GWT.log("Loading Visualizers panel");
		super.onLoad();
	}

	@Override
	public void onValueChange(ValueChangeEvent<String> arg0) {
		GWT.log("onValueChange");
		
	}

	public void showVisualizers(List<VisualizerDTO> visualizers) {
		visualizersGrid.clear();
		visualizersGrid.resizeRows(visualizers.size() + 1);
		visualizersGrid.setBorderWidth(2);
		visualizersGrid.setSize("100%", "100%");
		int i = 1;
		this.addHeader(visualizersGrid);
		for(VisualizerDTO visualizer:visualizers) {
			this.addRow(i, visualizersGrid, visualizer);
			i++;
		}
	}
	
	private void addHeader(Grid grid) {
		GWT.log("Adding Header");
		grid.setText(0, 0, "Name");
		grid.setText(0, 1, "Monitors");
		grid.setText(0, 2, "URL");
		
	}

	private void addRow(int rowNum, Grid grid, VisualizerDTO visualizer) {
		grid.setText(rowNum, 0, visualizer.getName());
		grid.setWidget(rowNum, 1, this.assembleMonitorsText(visualizer));
		grid.setText(rowNum, 2, visualizer.getConnectionUrl());
		
	}

	/**
	 * Devuelve el HTML armado para mostrar los monitors como bullets
	 * @param visualizer
	 * @return
	 */
	private Widget assembleMonitorsText(VisualizerDTO visualizer) {
		if(visualizer.getMonitors().isEmpty()) {
			return new HTML("all");
		}
		StringBuffer buffer = new StringBuffer();
		buffer.append("<ul>");
		for(String monitor:visualizer.getMonitors()) {
			buffer.append("<li>" + monitor);
		}
		buffer.append("</ul>");
		return new HTML(buffer.toString());
	}

}
